"""
UI自动化相关数据库模型
"""

from sqlalchemy import Column, Integer, String, Text, Boolean, DateTime, ForeignKey, Enum
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from enum import Enum as PyEnum
from ..core.database import Base


class UiAutomationStatus(PyEnum):
    """UI自动化脚本状态"""
    DRAFT = "draft"          # 草稿
    ACTIVE = "active"        # 激活
    INACTIVE = "inactive"    # 停用


class ExecutionStatus(PyEnum):
    """执行状态"""
    PENDING = "pending"      # 待执行
    RUNNING = "running"      # 执行中
    SUCCESS = "success"      # 成功
    FAILED = "failed"        # 失败
    CANCELLED = "cancelled"  # 已取消


class UiAutomationScript(Base):
    """UI自动化脚本表"""
    __tablename__ = "ui_automation_scripts"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(200), nullable=False, comment="脚本名称")
    description = Column(Text, comment="脚本描述")
    requirement_id = Column(Integer, ForeignKey("requirements.id"), comment="关联需求ID")
    yaml_content = Column(Text, nullable=False, comment="YAML脚本内容")
    status = Column(Enum(UiAutomationStatus), default=UiAutomationStatus.DRAFT, comment="脚本状态")
    tags = Column(String(500), comment="标签，多个标签用逗号分隔")
    created_by = Column(Integer, ForeignKey("users.id"), nullable=False, comment="创建人")
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), comment="更新时间")

    # 关联关系
    requirement = relationship("Requirement", back_populates="ui_automation_scripts")
    creator = relationship("User")
    executions = relationship("UiAutomationExecution", back_populates="script", cascade="all, delete-orphan")


class UiAutomationExecution(Base):
    """UI自动化执行记录表"""
    __tablename__ = "ui_automation_executions"

    id = Column(Integer, primary_key=True, index=True)
    script_id = Column(Integer, ForeignKey("ui_automation_scripts.id"), nullable=False, comment="脚本ID")
    execution_name = Column(String(200), comment="执行名称")
    status = Column(Enum(ExecutionStatus), default=ExecutionStatus.PENDING, comment="执行状态")
    start_time = Column(DateTime(timezone=True), comment="开始时间")
    end_time = Column(DateTime(timezone=True), comment="结束时间")
    duration = Column(Integer, comment="执行时长(秒)")
    success_count = Column(Integer, default=0, comment="成功任务数")
    failed_count = Column(Integer, default=0, comment="失败任务数")
    total_count = Column(Integer, default=0, comment="总任务数")
    error_message = Column(Text, comment="错误信息")
    result_data = Column(Text, comment="执行结果JSON数据")
    execution_options = Column(Text, comment="执行选项JSON数据")
    execution_type = Column(String(20), default='single', comment="执行类型：单个或批量")
    script_name = Column(String(200), comment="脚本名称")
    report_file_name = Column(String(500), comment="报告文件名")
    execution_logs = Column(Text, comment="执行日志输出")
    result_json_path = Column(String(500), comment="结果JSON文件路径")
    screenshots_path = Column(String(500), comment="截图保存路径")
    logs_path = Column(String(500), comment="日志保存路径")
    executed_by = Column(Integer, ForeignKey("users.id"), nullable=False, comment="执行人")
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")

    # 关联关系
    script = relationship("UiAutomationScript", back_populates="executions")
    executor = relationship("User")
    task_results = relationship("UiTaskResult", back_populates="execution", cascade="all, delete-orphan")


class UiTaskResult(Base):
    """UI任务执行结果表"""
    __tablename__ = "ui_task_results"

    id = Column(Integer, primary_key=True, index=True)
    execution_id = Column(Integer, ForeignKey("ui_automation_executions.id"), nullable=False, comment="执行记录ID")
    task_name = Column(String(200), nullable=False, comment="任务名称")
    task_index = Column(Integer, nullable=False, comment="任务序号")
    status = Column(Enum(ExecutionStatus), nullable=False, comment="任务状态")
    start_time = Column(DateTime(timezone=True), comment="开始时间")
    end_time = Column(DateTime(timezone=True), comment="结束时间")
    duration = Column(Integer, comment="执行时长(毫秒)")
    step_count = Column(Integer, default=0, comment="步骤总数")
    success_steps = Column(Integer, default=0, comment="成功步骤数")
    failed_steps = Column(Integer, default=0, comment="失败步骤数")
    error_message = Column(Text, comment="错误信息")
    result_data = Column(Text, comment="任务结果JSON数据")
    screenshot_urls = Column(Text, comment="截图URL列表，JSON格式")

    # 关联关系
    execution = relationship("UiAutomationExecution", back_populates="task_results")
    step_results = relationship("UiStepResult", back_populates="task", cascade="all, delete-orphan")


class UiStepResult(Base):
    """UI步骤执行结果表"""
    __tablename__ = "ui_step_results"

    id = Column(Integer, primary_key=True, index=True)
    task_id = Column(Integer, ForeignKey("ui_task_results.id"), nullable=False, comment="任务ID")
    step_index = Column(Integer, nullable=False, comment="步骤序号")
    step_type = Column(String(50), nullable=False, comment="步骤类型")
    step_content = Column(Text, comment="步骤内容")
    status = Column(Enum(ExecutionStatus), nullable=False, comment="步骤状态")
    start_time = Column(DateTime(timezone=True), comment="开始时间")
    end_time = Column(DateTime(timezone=True), comment="结束时间")
    duration = Column(Integer, comment="执行时长(毫秒)")
    error_message = Column(Text, comment="错误信息")
    screenshot_url = Column(String(500), comment="步骤截图URL")
    result_data = Column(Text, comment="步骤结果JSON数据")

    # 关联关系
    task = relationship("UiTaskResult", back_populates="step_results")


class UiAutomationBatch(Base):
    """UI自动化批量执行表"""
    __tablename__ = "ui_automation_batches"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(200), nullable=False, comment="批量执行名称")
    description = Column(Text, comment="批量执行描述")
    script_ids = Column(Text, nullable=False, comment="脚本ID列表，JSON格式")
    total_scripts = Column(Integer, default=0, comment="脚本总数")
    completed_scripts = Column(Integer, default=0, comment="已完成脚本数")
    success_scripts = Column(Integer, default=0, comment="成功脚本数")
    failed_scripts = Column(Integer, default=0, comment="失败脚本数")
    status = Column(Enum(ExecutionStatus), default=ExecutionStatus.PENDING, comment="批量执行状态")
    start_time = Column(DateTime(timezone=True), comment="开始时间")
    end_time = Column(DateTime(timezone=True), comment="结束时间")
    duration = Column(Integer, comment="执行时长(秒)")
    created_by = Column(Integer, ForeignKey("users.id"), nullable=False, comment="创建人")
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")

    # 关联关系
    creator = relationship("User")
